import time
import datetime

from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info import user_login_data
from info.models import User, News, Category
from info.utils.image_storage import image_storage
from info.utils.response_code import RET
from . import admin_blue
# ××××××××××××××××× 首页登陆×××××××××××
@admin_blue.route("/index")
@user_login_data
def index():
    admin = g.user.to_dict() if g.user else ""
    return render_template("admin/index.html", admin = admin)

# *************管理员登陆页面***********
@admin_blue.route("/login", methods = ["GET", "POST"])
def admin_login():
    # 如过是GET请求返回页面
    if request.method == "GET":
        # 判断管理员是否登陆过
        if session.get("is_admin"):
            return redirect(url_for("admin.index"))
        return render_template("admin/login.html")
    # 如果是POST请求获取参数
    username  = request.form.get("username")
    password  = request.form.get("password")
    # 校验参数为空校验
    if not all([username, password]):
        return render_template("admin/login.html", errmsg = "参数不完整 ")
    # 根据用户名取出管理员对象， 判断管理员是否存在
    try:
        admin = User.query.filter(User.mobile == username, User.is_admin== True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg = "管理员获取失败 ")
    if not admin:
        return render_template("admin/login.html", errmsg = "管理员不存在 ")

    # 校验密码
    if not admin.check_password(password):
        return render_template("admin/login.html", errmsg = "管理员密码错误 ")
    # 记录管理员密码到session中
    session["user_id"] = admin.id
    session["nick_name"] = admin.nick_name
    session["mobile"] = admin.mobile
    session["is_admin"] = True
    # 重定向到首页
    return redirect(url_for("admin.index"))
# *************用户图表统计××××××××××××
@admin_blue.route("/user_count")
def user_count():
    # 查询总人数
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_count.html", data = {"errmsg": "用户查询总人数失败"})
    # 查询月活人数
    cal = time.localtime()
    try:
        # 本月一号0点
        start_mon_str = "%d-%d-01"%(cal.tm_year, cal.tm_mon)
        # 转日期对象
        start_mon_date = datetime.datetime.strptime(start_mon_str,"%Y-%m-%d") #2018-11-01 00:00:00
        # 查询月活人数
        mon_count = User.query.filter(User.last_login>=start_mon_date, User.is_admin == False).count()

    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_count.html", data = {"errmsg": "用户查询月活人数失败"})
    # 查询日活人数
    cal = time.localtime()
    try:
        # 本日0点
        start_day_str = "%d-%d-%d"%(cal.tm_year, cal.tm_mon, cal.tm_mday)
        # 转日期对象
        start_day_date = datetime.datetime.strptime(start_day_str, "%Y-%m-%d")# 2018-11-12 00:00:00
        # 查询日活人数
        day_count = User.query.filter(User.last_login>=start_day_date, User.is_admin== False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_count.html", data = {"errmsg": "用户查询日活人数失败"})
    # 对应时间段对应活跃人数
    active_date = []  # 获月日期段
    active_count = []  # 活跃日期段对应的人数
    for i in range(0,30):
        # 当天开始的时间
        begin_date = start_day_date-datetime.timedelta(days=i)
        # 当天开始时间的后一天
        end_date = start_day_date-datetime.timedelta(days=i-1)
        # 添加到活跃日期段
        active_date.append(begin_date.strftime("%m-%d"))
        # 查询一天的注册人数
        everyday_active_count = User.query.filter(User.is_admin==False,User.last_login>=begin_date,User.last_login<=end_date).count()
        # 添加当天的注册人数到active_count
        active_count.append(everyday_active_count)
    # 反转容器
    active_date.reverse()
    active_count.reverse()
    # 拼接数据渲染页面
    data = {
        "total_count":total_count,
        "mon_count": mon_count,
        "day_count":day_count,
        "active_date":active_date,
        "active_count":active_count
    }
    return render_template("admin/user_count.html", data=data )

# **************新闻分页查询××××××××××
@admin_blue.route("/user_list")
def user_list():
    # 获取参数
    page = request.args.get("p", "1")
    # 转换类型
    try:
        page = int(page)
    except Exception as e:
        page = 1
    # 分页查询
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.create_time.desc()).paginate(page, 10,False)
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_list.html", data = {"errmsg": "获取用户失败"})
    # 获取分页对象属性，总页数，当前页，对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    # 对象列表转换成字典列
    user_list = []
    for item in items:
        user_list.append(item.to_admin_dict())
    # 拼接数据渲染页面
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "user_list": user_list
    }
    return render_template("admin/user_list.html", data=data)

# **************新闻审核列表获取×××××××
@admin_blue.route("/news_review")
def news_review():
    # 获取参数
    page = request.args.get("p", "1")
    keysword = request.args.get("keysword")
    # 转换类型
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 分页查询
    try:
        filters = [News.status != 0]
        # 判断是否输入了关键字
        if keysword:
            filters.append(News.title.contains(keysword))
        paginate = News.query.filter( *filters).order_by(News.create_time.desc()).paginate(page, 10, False)
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/news_review.html", data={"errmsg": "获取新闻失败"})
    # 获取分页对象属性，总页数，当前页，对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    # 对象列表转换成字典列
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())
    # 拼接数据渲染页面
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }
    return render_template("admin/news_review.html", data=data)

# *************获取新闻审核详情××××××××
@admin_blue.route("/news_review_detail", methods = ["GET", "POST"])
@admin_blue.route('/news_review_detail',methods=["GET","POST"])
def news_review_detail():
    #1.判断请求方式,如果是GET
    if request.method == "GET":

        news_id = request.args.get("news_id")

        if not news_id: return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

        #2.根据编号查询新闻,渲染页面
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

        if not news: return jsonify(errno=RET.NODATA,errmsg="新闻不存在")

        return render_template("admin/news_review_detail.html",news=news.to_dict())

    #3.如果是POST,获取请求参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    #4.校验参数,为空校验
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #5..判断操作类型
    if not action in ["accept","reject"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")

    #6.根据新闻编号,取出新闻对象,并判断是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    if not news: return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    #7.根据操作类型,修改新闻状态
    if action == "accept":
        news.status = 0
    else:
        news.reason = request.json.get("reason","")
        news.status = -1

    #8.返回响应
    return jsonify(errno=RET.OK,errmsg="操作成功")

# *************  新闻版式编辑×××××××××
@admin_blue.route("/news_edit")
def news_edit():
    # 获取参数
    page = request.args.get("p", "1")
    keysword = request.args.get("keysword")
    # 转换类型
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 分页查询
    try:
        filters = []
        # 判断是否输入了关键字
        if keysword:
            filters.append(News.title.contains(keysword))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, 10, False)
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/news_edit.html", data={"errmsg": "获取新闻失败"})
    # 获取分页对象属性，总页数，当前页，对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    # 对象列表转换成字典列
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())
    # 拼接数据渲染页面
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }
    return render_template("admin/news_edit.html", data=data)

# *************  新闻版式编辑详情×××××××××
@admin_blue.route("/news_edit_detail", methods = ["GET", "POST"])
def news_edit_detail():
    # 1.判断请求方式,如果是GET
    if request.method == "GET":

        news_id = request.args.get("news_id")

        if not news_id: return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

        # 2.根据编号查询新闻,渲染页面
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

        if not news: return jsonify(errno=RET.NODATA, errmsg="新闻不存在")
        # 查询所有分类信息，并转成字典
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return  jsonify(errno = RET.DBERR, errmsg ="获取分类失败")
        category_list = []
        for category in categories:
            category_list.append(category)

        return render_template("admin/news_edit_detail.html", news=news.to_dict(),categories = category_list)
    #2.获取post提交的参数,news_id,title,digest,content,index_image,category_id
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    category_id = request.form.get("category_id")
    index_image = request.files.get("index_image")

    #3.校验参数,为空校验
    if not all([news_id,title,digest,content,category_id,index_image]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #4.根据新闻编号取出新闻对象,并判断是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    if not news: return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    #5.上传图片,判断图片是否存在
    try:
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云异常")

    if not image_name: return jsonify(errno=RET.NODATA,errmsg="上传图片失败")

    #6.修改新闻数据
    try:
        news.title= title
        news.digest = digest
        news.content = content
        news.category_id = category_id
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    except Exception as e:
        return jsonify(errno=RET.DBERR,errmsg="修改失败")

    #7.返回响应
    return jsonify(errno=RET.OK,errmsg="修改成功")

# ************获取所有分类 ×××××××××××××
@admin_blue.route("/news_category")
def news_category():
    # 查询所有分类
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = "获取分类失败")
    # 分类对象转成字典列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    # 携带数据渲染页面
    return render_template("admin/news_type.html", categories = category_list)

# ************新闻分类添加修改×××××××××××
@admin_blue.route("/add_category", methods = ["POST"])
def add_category():
    # 获取参数
    category_id = request.json.get("id")
    category_name = request.json.get("name")
    # 校验参数为空校验
    if not category_name:
        return jsonify(errno = RET.NODATA, errmsg = "参数不全")
    # 根据分类编号判断增加还是编辑
    if category_id:
        # 判断分类对象是否存在、
        try:
            # 根据分类编号查询分类对象
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR, errmsg = '获取分类失败')
        if not category: return jsonify(errno = RET.NODATA, errmsg = "分类不存在")
        # 修改分类名称
        category.name = category_name
    else:  # 增加
        # 创建分类对象,设置属性
        catetory = Category()
        catetory.name = category_name

        # 保存到数据库中
        try:
            db.session.add(catetory)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="分类创建失败")

    # 4.返回响应
    return jsonify(errno=RET.OK, errmsg="操作成功")

